package com.nmgydy.admin.controller;

import com.alibaba.fastjson.JSON;
import com.nmgydy.model.Admin;
import com.nmgydy.beans.Message;
import com.nmgydy.util.*;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/admin")
public class AdminController {
	@Resource
	private HibernateDao hibernateDao;

	@RequestMapping(value = "home")
	public String home() {
		return "admin/home";
	}

	@RequestMapping(value = "login")
	public String getLogin(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "admin/login";
	}

	/**
	 * 验证码
	 */
	@RequestMapping("/randCheckCode")
	public ModelAndView getRandCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		RandCheckCode.getCode(request, response, "randCheckCode");
		return null;

	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String captcha = request.getParameter("captcha");
		Assert.assertNotNull(username, "username is null");
		Assert.assertNotNull(password, "password is null");
		Assert.assertNotNull(captcha, "captcha is null");
		Message message = new Message();
		String rand = (String) request.getSession().getAttribute("randCheckCode");
		request.getSession().setAttribute("randCheckCode", null);// 登录一次后验证码失效
		if (rand == null || !rand.equals(captcha)) {
			message.setRes(false);
			message.setMsg("验证码不正确");
			return JSON.toJSONString(message);
		}
		Session session = null;
		try {
			//password = Secret.encodeMD5(password + "studentms-mobile"); // 加密
			//System.out.println(password);
			session = hibernateDao.getSessionFactory().openSession();
			String hql = "select a from Admin a where a.username=:username and a.password=:password";
			Query q = session.createQuery(hql);
			q.setParameter("username", username);
			q.setParameter("password", password);
			Admin admin = (Admin) q.uniqueResult();
			if (admin == null) {
				message.setRes(false);
				message.setMsg("用户名或密码错误");
				return JSON.toJSONString(message);
			} else {
				request.getSession().setAttribute("admin", admin);
				message.setRes(true);
				message.setMsg("登录成功");
				return JSON.toJSONString(message);
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
			message.setRes(false);
			message.setMsg("系统错误");
			return JSON.toJSONString(message);
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@RequestMapping(value = "logout")
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		/*
		 * Enumeration<String> em = request.getSession().getAttributeNames();
		 * while (em.hasMoreElements()) {
		 * request.getSession().removeAttribute(em.nextElement().toString()); }
		 */
		String contextPath = request.getContextPath();
		request.getSession().invalidate();

		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		response.sendRedirect(contextPath + "/admin/login");
		return null;
	}

	@RequestMapping(value = "edit_password")
	public String edit_password(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "admin/edit_password";
	}

	@RequestMapping(value = "passwordUpdate")
	@ResponseBody
	public String passwordUpdate(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		String oldpassword = request.getParameter("oldpassword");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		String rootPath = request.getContextPath();
		System.out.println(rootPath);
		Admin adminUser = (Admin) request.getSession().getAttribute("admin");
		Assert.assertNotNull(adminUser, "adminUser is null");
		if (oldpassword.equals(password)) {
			return JSON.toJSONString(new Message(false, "新密码与原密码输入一致！"));
		}

		if (password.equals(repassword)) {
			Session session = null;
			Long total = (long) 0;
			try {
				session = hibernateDao.getSessionFactory().openSession();
				//oldpassword = Secret.encodeMD5(oldpassword + "studentms-mobile"); // 加密
				String hql = "select count(a) from Admin a where  a.password=:password";
				Query q = session.createQuery(hql);
				q.setParameter("password", oldpassword);
				total = (Long) q.uniqueResult();
			} catch (Exception e) {
				response.getWriter().write("<script>window.location.href='" + rootPath + "admin/'</script>");
				return null;
			} finally {
				if (session != null) {
					session.close();
				}
			}

			if (total == 0) {
				return JSON.toJSONString(new Message(false, "原密码输入错误，请重新输入！"));
			}

			try {
				session = hibernateDao.getSessionFactory().openSession();
				Transaction transaction = session.beginTransaction();
				//password = Secret.encodeMD5(password + "studentms-mobile"); // 加密

				String hql = "update Admin a set a.password=:password where a.id=:id";
				session.createQuery(hql).setParameter("password", password).setParameter("id", adminUser.getId()).executeUpdate();
				transaction.commit();
			} catch (Exception e) {
				return JSON.toJSONString(new Message(false, "修改密码失败！"));
			} finally {
				if (session != null) {
					session.close();
				}
			}
		} else {
			return JSON.toJSONString(new Message(false, "两次输入密码不一致！"));
		}

		return JSON.toJSONString(new Message(true, "修改密码成功，请重新登陆！"));
	}

	@RequestMapping(value = "checkAudit")
	@ResponseBody
	public String checkAudit(Integer moduleId,HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		if(moduleId == null){
			return JSON.toJSONString(new Message(false, "moduleId is null"));
		}
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		int[] ids = Arrays.stream(admin.getRoleIds().split(",")).mapToInt(Integer::parseInt).toArray();
		String hql = "from ModuleRole where moduleId=:moduleId and roleId in (:ids)";
		Map<String,Object> params = new HashMap<>();
		params.put("moduleId",moduleId);
		params.put("ids",ids);
		List<?> list = hibernateDao.list(hql,params);
		if(list.size() > 0){
			return JSON.toJSONString(new Message(true, "获取成功"));
		}else{
			return JSON.toJSONString(new Message(false, "您没有这个操作权限"));
		}
	}
}
